#include "../mds/io/mds.h"
#include "../mds/io/xyz.h"
#include "../mds/sys/string.h"

typedef struct
{
	const char *filename;
	int         append;
	const char *energy;
} param_t;

static
int do_save( const mds_frame *frame, Real t, void *args )
{
	
	param_t *param  = args;
	char    *comment = NULL;
	assert( param ); assert( param->filename );
	assert( frame );
	comment = mds_string( "t=%8.3lf", (double)t );
	if( !comment )
		return -1;
	
	if( mds_xyz_save( param->filename, frame->sets[MDS_POSITION], frame->num_particles, comment, param->append) < 0 )
	{
		mds_string_delete(comment);
		return -1;
	}
	
	if( param->energy )
	{
		char mode[4] = { param->append ? 'a' : 'w', 'b', 0, 0 };
		FILE *fp = fopen( param->energy, mode );
		Real T=0, PV=0;
		if( !fp )
			return -1;
		if( !param->append )
		{
			fprintf( fp, "#t V K E W T PV\n" );
		}
		mds_frame_NVE_T_and_PV(frame,&T,&PV);
		fprintf(fp, "%.6e %.6e %.6e %.6e %.6e %.6e %.6e\n", t, frame->V, frame->K, frame->V + frame->K, frame->W, T, PV);
		fclose( fp );
	}
	
	mds_string_delete(comment);
	param->append = 1;
	return 0;
}

#include "../mds/constants.h"

int main(int argc, char *argv[])
{
	
	MDS_R = 1;
	if( argc <= 2 )
	{
		fprintf( stdout, "usage: %s input_file output_file [energy_file]\n", argv[0]);
		return -1;
	}
	else
	{
		param_t param = { argv[2], 0, argv[3] };		
		MDS_MEMORY();
		mds_file_load_and_apply(argv[1], do_save, & param );
	}

	MDS_MEMORY();
	return 0;
}
